<template>
  <q-dialog v-model="show" persistent>
    <q-card v-drag class="dialog-content batch-bundling" style="min-width: 1000px; max-height: 700px">
      <q-card-section class="dialog-title bg-primary" >
        <div class="text-center text-white dialog-title">
          <span class="font-size-16" v-if="type == 'operator'">
            批量绑定操作员
          </span>
          <span v-else-if="type == 'technician'">
            批量绑定技术员
          </span>
        </div>
      </q-card-section>
      <q-card flat class="my-card detail" style="margin: 20px">
        <q-card-section class="dialog-title bg-primary details dialog-title">
          <span class="text-white font-size-16">
            所选设备
          </span>
        </q-card-section>
        <q-card-section class="bordered" style="padding: 10px 10px">
          <q-scroll-area :thumb-style="thumbStyle" style="height: 80px">
            <div class="sel-item"  v-for="(item,index) in batchBund" :key="index">
              <div class="flex justify-between items-center">
                <div class="txt font-size-16">
                  {{item.deviceName}}（{{item.assetNumber}}）
                </div>
                <q-icon @click="delItem(index)" class="close fr font-size-16" name="iconfont icontubiao-89" />
              </div>
            </div>
          </q-scroll-area>
        </q-card-section>
      </q-card>
      <div style="margin: 0 20px; padding-bottom: 20px" class="flex items-center">
        <select-input :list="searchCondition" @search="inputSearch" @clearSearchVal="clearSearchVal"/>
        <div class="form-inline" style="padding: 0;margin-left: 120px" >
          <q-select
            class="select"
            outlined dense emit-value map-options options-dense
            :options="shiftsList"
            v-model="shift"
          >
            <template v-slot:no-option>
              <div class="no-option"/>
            </template>
            <template v-slot:before>
              <span class="form-name">轮班:</span>
            </template>
          </q-select>
        </div>
      </div>
      <unfold style="padding: 0 20px 20px">
        <!-- 左侧组名称列表 -->
        <template v-slot:tree-list>
          <div class="left box tree-list">
            <!-- 列表 -->
            <div  style="height: 336px" class="tree-content bg-white overflow-auto scrollbar">
              <div v-for="(item, index) in treeList" :key="index">
                <tree-item :item="item" :activeId="activeId" :ellipsis="false" v-if="item.type != 'cc' && item.type != 'cg'" />
              </div>
            </div>
          </div>
        </template>
        <template v-slot:content>
          <div class="right box page-content " style="display: flex;position: relative;flex-direction: column; height: 338px">
              <!-- 表格 -->
              <q-table
                class="users-table myTable scroll my-sticky-virt scroll-table bor scroll-bor inherit"
                :columns="tableColumns"
                :data="users"
                row-key="id"
                :pagination.sync="pagination"
                selection="single"
                :selected.sync="selectedUsers"
                color="primary"
                :hide-bottom="!!users.length"
                style="margin: 0;max-height: 336px"
              >
                <template v-slot:body="props">
                  <q-tr :props="props">
                    <q-td auto-width>
                      <q-radio dense v-model="selectedUsers[0].id" :val="props.row.id" />
                    </q-td>
                    <q-td>
                      {{ props.row.number}}
                    </q-td>
                    <q-td>
                      {{ props.row.name}}
                    </q-td>
                    <q-td>
                      {{ getRoleNamesByRoles(props.row.roles) }}
                      <q-tooltip v-if="getRoleNamesByRoles(props.row.roles)">{{ getRoleNamesByRoles(props.row.roles) }}</q-tooltip>
                    </q-td>
                    <q-td>{{getPostNameByCode(props.row.postCode)}}</q-td>
                  </q-tr>
                </template>
              </q-table>
<!--                <pagination-->
<!--                  v-model="pagination.page"-->
<!--                  :page-size="pagination.rowsPerPage"-->
<!--                  :total="pagination.rowsNumber"-->
<!--                  @changePageSize="onPageSizeChange"-->
<!--                  @changePage="onPageChange"-->
<!--                />-->
            <!-- 表格End -->
          </div>
        </template>
      </unfold>
      <!-- 底部按钮 -->
      <q-separator />
      <div class="dialog-footer text-center margin-t-10">
        <q-btn outline label="取消" color="primary" @click="$emit('close')" class="q-mr-md"/>
        <q-btn unelevated label="确认" color="primary" :disable="batchBund.length == 0 || selectedUsers[0].id == null || isDisable" @click="submitData"/>
      </div>
    </q-card>
  </q-dialog>
</template>

<script>
import Unfold from 'src/components/unfold'
import TreeItem from 'src/components/tree-list/item'
import SelectInput from '../../../components/select-input/index'
import { gethashcode } from '../../../assets/js/util'
import userManageApi from '../../../boot/system/user-manage'
import { batchBind } from '../../../boot/job/man-machine-bind'

export default {
  name: 'batch-bundling',
  components: {
    SelectInput,
    Unfold,
    TreeItem
  },
  props: {
    show: {
      type: Boolean,
      default: false,
      required: false
    },
    batchBund: {
      default: [],
      required: false
    },
    type: {
      type: String,
      default: '',
      required: true
    },
    // 列表数据
    list: {
      type: Array
    },
    postOptions: {
      required: true
    },
    shiftsList: {
      required: true
    },
    workshopId: {
      required: true
    }
  },
  data () {
    return {
      searchCondition: [{ id: 'name', name: '人名' }, { id: 'number', name: '员工编号' }],
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      shiftOptions: [{
        value: 'all',
        label: '全部'
      }],
      // 使用到的数据
      treeList: [],
      // 选中的idHash
      activeId: null,
      // form 正在提交
      isSubmitting: false,
      shift: 'all', // 轮班下拉选中项
      // 表格列
      tableColumns: [
        { name: 'number', field: 'number', label: '员工编号', align: 'left' },
        { name: 'name', field: 'name', label: '姓名', align: 'left' },
        { name: 'roles', field: 'roles', label: '角色', align: 'left' },
        { name: 'post', field: 'post', label: '岗位', align: 'left' }
      ],
      // 用户数组
      users: [],
      // 表格分页配置
      pagination: {
        rowsPerPage: 0
      },
      // 查询参数
      queryParams: {
        searchBy: '', // 搜索条件 name 人名
        keyword: '', // 搜索值
        // 部门 ID
        departmentId: null
      },
      // 选中的用户
      selectedUsers: [{
        id: null
      }],
      isDisable: false
    }
  },
  mounted () {
    // 监听change-activeid，设置activeId
    this.CommonConfig.event.$on('change-activeid', (id, item) => {
      if (this.queryParams.departmentId !== item.id) {
        this.activeId = id
        this.queryParams.departmentId = item.id
        this.listUsers()
      }
    })
  },
  methods: {
    // 给list添加数据
    initTree (info, open = true) {
      return info.map(item => {
        if (item.children && item.children.length > 0) {
          item.children = this.initTree(item.children)
        }
        return {
          ...item,
          open,
          idHash: gethashcode()
        }
      })
    },
    // 搜索
    inputSearch (item, searchVal) {
      this.queryParams.searchBy = item.id
      this.queryParams.keyword = searchVal
      this.pagination.page = 1
      this.listUsers()
    },
    // 清空
    clearSearchVal () {
      this.queryParams.searchBy = ''
      this.queryParams.keyword = ''
      this.listUsers()
    },
    /**
     * 列举用户
     */
    listUsers () {
      this.users = []
      userManageApi.listUsersNoPage(this.queryParams)
        .then(data => {
          // selectedUsers
          if (data.length > 0) {
            this.selectedUsers[0].id = data[0].id
          } else {
            this.selectedUsers[0].id = null
          }

          this.users = data
          // this.pagination.rowsNumber = data.total
        })
        .finally(() => {
          this.isTableLoading = false
        })
    },
    /**
     * 根据角色对象数组获取拼接的角色名
     * @param roles 角色对象数组
     * @return {string} 拼接的角色名
     */
    getRoleNamesByRoles: function (roles) {
      let names = ''
      for (let i in roles) {
        let role = roles[i]
        if (role === undefined) {
          break
        }
        names += ', ' + role.name
      }
      names = names.substr(2)

      return names
    },
    // 获取岗位名
    getPostNameByCode (id) {
      let label = ''
      if (id) {
        this.postOptions.forEach(item => {
          if (item.value === id) {
            label = item.label
          }
        })
      }
      return label
    },
    setTree (list) {
      this.treeList = this.initTree(list)
      // 首次指定部门
      if (!this.activeId) {
        this.treeList.forEach(item => {
          if (!this.activeId && item.type !== 'cc' && item.type !== 'cg') {
            this.activeId = item.idHash
            this.queryParams.departmentId = item.id
          }
        })
      }
      this.listUsers()
    },
    // 删除所选设备
    delItem (index) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定删除该所选设备吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      })
        .onOk(() => {
          this.batchBund.splice(index, 1)
        })
    },
    // 提交
    submitData () {
      this.isDisable = true
      let paramsItem = {
        userId: this.selectedUsers[0].id,
        workshopId: this.workshopId,
        userType: this.type
      }
      let shiftIds = []
      if (this.shift === 'all') {
        this.shiftsList.forEach(i => {
          if (i.value !== 'all') {
            shiftIds.push(i.value)
          }
        })
      } else {
        shiftIds.push(this.shift)
      }
      paramsItem.shiftIds = shiftIds
      let deviceIds = []
      this.batchBund.forEach(i => {
        deviceIds.push(i.deviceId)
      })
      paramsItem.deviceIds = deviceIds
      let label = '是否覆盖当前绑定'
      if (this.type === 'operator') {
        label += '操作员？'
      } else if (this.type === 'technician') {
        label += '技术员？'
      }
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>${label}</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      })
        .onOk(() => {
          batchBind(paramsItem).then(res => {
            if (res.code === '1200') {
              this.isDisable = false
              this.$emit('close')
              this.$emit('getBindingList')
              this.$message.success('批量绑定成功')
            }
          })
        })
        .onCancel(() => {
          this.isDisable = false
        })
    }
  },
  watch: {
    show: function () {
      this.queryParams.searchBy = ''
      this.queryParams.keyword = ''
      this.shift = 'all'
      this.activeId = null
      if (this.show) {
        this.setTree(this.list)
      }
    }
  }
}
</script>

<style scoped lang="stylus">
  .batch-bundling{
    /*>>>.users-table .q-table__middle.scroll{
      height 100%
    }*/
    .font-size-16 {
      font-size 16px
    }
    .font-size-14 {
      font-size 14px
    }
    .bordered,.bordered:last-child {
      border 1px solid #D3D3D3
      border-bottom  1px
      border-top 0
      border-bottom-left-radius: 6px;
      border-bottom-right-radius: 6px;
    }
    .details{
      border-top-left-radius: 6px;
      border-top-right-radius: 6px;
      padding 0 24px
    }
    .dialog-title .close-btn{
      position absolute
      right 0
    }
    .item{
      background-color $secondary !important
    }
    >>>.q-chip__icon--remove{
      content 'iconfont icontubiao-89'
    }
    .cursor-move{
      cursor move
    }
    .sel-item{
      display inline-block
      min-width 100px
      background-color $secondary
      color #fff
      padding 4px 8px
      border-radius 6px
      margin-bottom 10px
      margin-right 10px
      .close{
        margin-left 10px
        opacity .6
      }
      .close:hover{
        opacity 1
      }
    }&.sel-item:first-child{
       margin-left 0
     }
    >>>.toggle-hide{
      display none
    }
    .tree-list {
      display flex
      flex-direction column
      width 300px
      border-radius 6px
      overflow hidden
      height 338px
      border 1px #D3D3D3 solid

      .tree-content {
        flex 1
        min-height calc(100% - 40px)
        /*padding-bottom 20px*/
      }

      .toggle-icon {
        transition transform 300ms ease-in

        &.fold {
          transform rotate(-90deg)
        }
      }
    }
    >>>.tree-bg .tree-line{
      border none
      height: 32px;
      line-height: 32px;
    }
    >>>.dialog-content .name{
      font-size 16px
    }
    >>>.fold .left-part{
      min-width: 300px;
      max-width: 300px;
    }
    >>>.right-part{
      padding 0 !important
    }
    >>>.left-part{
      margin-right: 20px !important;
    }
  }
</style>
